import os
import json
import queue
import threading
from datetime import datetime
from PySide6.QtCore import QObject, Signal

class LogManager(QObject):
    log_config_changed = Signal(str)  # 日志配置改变信号
    
    def __init__(self):
        super().__init__()
        self.config_dir = os.path.expanduser('~/.a-terminal/settings')
        self.config_file = os.path.join(self.config_dir, 'logger.json')
        self.ensure_config_file()
        self.load_config()
        
        # 初始化异步日志写入锁
        self.log_lock = threading.Lock()
        
    def ensure_config_file(self):
        """确保配置文件存在"""
        os.makedirs(self.config_dir, exist_ok=True)
        if not os.path.exists(self.config_file):
            default_config = {
                'log_dir': os.path.join(os.path.expanduser('~/.a-terminal'), 'logs'),
                'enabled': True
            }
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(default_config, f, ensure_ascii=False, indent=4)
                
    def load_config(self):
        """加载日志配置"""
        with open(self.config_file, 'r', encoding='utf-8') as f:
            self.config = json.load(f)
        # 确保日志目录存在
        os.makedirs(self.config['log_dir'], exist_ok=True)
            
    def save_config(self):
        """保存日志配置"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(self.config, f, ensure_ascii=False, indent=4)
            
    def get_log_dir(self):
        """获取日志保存目录"""
        return self.config['log_dir']
    
    def set_log_dir(self, log_dir):
        """设置日志保存目录"""
        if os.path.isdir(log_dir):
            self.config['log_dir'] = log_dir
            self.save_config()
            self.log_config_changed.emit(log_dir)
            
    def is_logging_enabled(self):
        """检查日志功能是否启用"""
        return self.config['enabled']
    
    def set_logging_enabled(self, enabled):
        """设置日志功能启用状态"""
        self.config['enabled'] = enabled
        self.save_config()
        
    def get_log_file_path(self, session_name):
        """获取日志文件路径"""
        if not self.is_logging_enabled():
            return None
        return os.path.join(self.config['log_dir'], f"{session_name}.log")
    
    def write_log(self, log_file, content, module_name=None):
        """异步写入日志文件
        
        Args:
            log_file: 日志文件路径
            content: 日志内容
            module_name: 模块名称，仅用于应用日志
        """
        if not self.is_logging_enabled() or not log_file:
            return
            
        def _write():
            try:
                with self.log_lock:
                    # 检查是否为应用日志（app.log）
                    is_app_log = log_file.endswith('app.log')
                    
                    if is_app_log:
                        # 应用日志：添加时间戳和模块信息
                        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
                        module_info = f"[{module_name}]" if module_name else ""
                        formatted_content = f"[{timestamp}]{module_info} {content}"
                        if not formatted_content.endswith('\n'):
                            formatted_content += '\n'
                    else:
                        # 会话日志：保持原始内容，不做任何压缩或格式化处理
                        formatted_content = content
                    
                    # 写入日志文件
                    with open(log_file, 'a', encoding='utf-8') as f:
                        f.write(formatted_content)
                        
            except Exception as e:
                print(f"写入日志失败: {str(e)}")
                
        # 创建并启动写入线程
        write_thread = threading.Thread(target=_write, daemon=True)
        write_thread.start()